package com.lungle.warmdiary.app.view.me.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.TextView;

import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseActivity;
import com.lungle.warmdiary.app.base.BaseFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.content.db.DAOFactory;
import com.lungle.warmdiary.app.content.db.IndustryDAO;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.response.TesterIndustry;
import com.lungle.warmdiary.app.model.response.TesterStat;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.view.me.adapter.IndustryAdapter;
import com.umeng.analytics.MobclickAgent;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by zhangxueyuan on 16/10/7.
 * <p>
 * 亲测师行业徽章
 */
public class SelectIndustryFragment extends BaseFragment {

    private static final String SELECT_TAG_SCREEN = "select tag screen";

    public static final String RESPONSE = "select_result";

    @Bind(R.id.tv_limit_tip)
    TextView mTvLimitTip;
    @Bind(R.id.gv_container)
    GridView mGvContainer;
    private int catalog;

    private List<TesterIndustry> mTagList;
    private IndustryAdapter mAdapter;
    //todo 不用list
    private List<TesterIndustry> selectedList = new ArrayList<>();


    private int INDUSTRY_MAX_SELECTED = 1;
    private IndustryDAO industryDAO;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_tag;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(SELECT_TAG_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(SELECT_TAG_SCREEN);
        MobclickAgent.onPause(getActivity());

    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(getLayoutId(), container, false);
        ButterKnife.bind(this, view);
        initData();
        initView(view);
        if (industryDAO == null) {
            industryDAO = DAOFactory.getIndustryDAO();
        }
        return view;
    }

    @Override
    public void initView(View view) {
        BaseActivity baseActivity = (BaseActivity) getActivity();
        mTvLimitTip.setText(Html.fromHtml("只能选择<font color=#FA4848>1</font>个徽章"));
        baseActivity.setActionBarTitle("行业徽章");
    }

    List<TesterStat> pass;
    List<String> passString = new ArrayList<>();

    @Override
    public void initData() {
        catalog = getArguments().getInt("catalog");
        if (getArguments().getSerializable("select_tags") != null) {
            selectedList.addAll((Collection<? extends TesterIndustry>) getArguments().getSerializable("select_tags"));
        }
        pass = (List<TesterStat>) getArguments().getSerializable("pass");
        if (pass != null && pass.size() > 0) {
            for (TesterStat stat : pass) {
                LogUtils.printLogE("passString:" + stat.getIndustry());
                passString.add("" + stat.getIndustry());
            }
        }
        getTag(catalog);

    }


    private void getTag(int catalog) {
        showWaitDialog();
        Observable<Result<List<TesterIndustry>>> tags;

        tags = ApiFactory.getUserApi().getTesterIndustryList();

        tags.subscribeOn(Schedulers.newThread())
                .compose(this.<Result<List<TesterIndustry>>>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result<List<TesterIndustry>>>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        super.onCompleted();
                        hideWaitDialog();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onNext(Result<List<TesterIndustry>> tagResult) {
                        super.onNext(tagResult);
                        mTagList = tagResult.getData();
                        AppContext.setIndustryNum(mTagList.size());

                        for (TesterIndustry industry : mTagList) {
                            AppContext.setIndustry(industry.getId(), industry.getIcon(), industry.getName());
                        }

//                        if (industryDAO != null)
//                            industryDAO.insertAll(mTagList);


                        Iterator<TesterIndustry> sListIterator = mTagList.iterator();
                        while (sListIterator.hasNext()) {
                            TesterIndustry e = sListIterator.next();
                            if (passString.contains(e.getId())) {
                                sListIterator.remove();
                            }
                        }
//                        if (passString != null)
//                            for (int i = 0; i < mTagList.size(); i++) {
//                                if (passString.contains(mTagList.get(i).getId())) {
//                                    mTagList.remove(mTagList.get(i));
//                                }
//                            }
//                            for (TesterIndustry testerIndustry : mTagList) {
//                                if (passString.contains(testerIndustry.getId())) {
//                                    mTagList.remove(testerIndustry);
//                                }
//                            }
                        mAdapter = new IndustryAdapter(getActivity(), mTagList, selectedList, onMultItemClick);
                        mGvContainer.setAdapter(mAdapter);
                        mAdapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable(RESPONSE, (Serializable) selectedList);
        intent.putExtras(bundle);
        getActivity().setResult(TesterApplyFragment.REQUEST_INDUSTRY, intent);

        getActivity().finish();
        return true;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
        if (industryDAO != null)
            industryDAO.close();

    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.active_detail, menu);

        menu.findItem(R.id.login_menu_send);
    }


    IndustryAdapter.onMultiItemSelectListener onMultItemClick = new IndustryAdapter.onMultiItemSelectListener() {

        @Override
        public void onItemClick(View v, int Position, CheckBox checkBox, TextView textView) {

            if (checkBox.isChecked()) {
                checkBox.setChecked(false);
                textView.setSelected(false);
                selectedList.remove(0);

            } else {
                if (selectedList.size() >= INDUSTRY_MAX_SELECTED) {
                    selectedList.remove(0);
                }
                checkBox.setChecked(true);
                textView.setSelected(true);
                selectedList.add(mTagList.get(Position));
            }
            mAdapter.notifyDataSetChanged();

        }
    };
}